package com.test.controller;

import org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author : caili
 * @date : 13:47 2023/1/16
 */
@RestController
public class RabbitMqManageController {
    @Resource
    RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry;

    /**
     * 根据队列名称动态修改队列线程配置 避免服务重启
     *
     * @param queueName
     * @param concurrentConsumers
     * @param maxConcurrentConsumers
     * @return
     */
    @RequestMapping(value = "/dynamicEditMqConsumerNum")
    public String editMqConsumerNum(@RequestParam(value = "queueName") String queueName,
                                    @RequestParam(value = "concurrentConsumers") Integer concurrentConsumers,
                                    @RequestParam(value = "maxConcurrentConsumers") Integer maxConcurrentConsumers,
                                    @RequestParam(value = "prefetchCount") Integer prefetchCount) {
        Collection<MessageListenerContainer> listenerContainers = rabbitListenerEndpointRegistry.getListenerContainers();
        for (MessageListenerContainer container : listenerContainers) {
            SimpleMessageListenerContainer con = (SimpleMessageListenerContainer) container;
            //消息监听容器要消费的队列名称集合
            List<String> queueNamesList = Arrays.asList(con.getQueueNames());
            //判断容器中的队列名称是否包含需要调整的队列名参数
            if (queueNamesList.contains(queueName)) {
                //注意先设置最大的消费者数量,再设置最小的消费者数量,因为先修改最小数量超过修改前的最大数量时会报异常修改失败
                con.setMaxConcurrentConsumers(maxConcurrentConsumers);
                con.setConcurrentConsumers(concurrentConsumers);
                con.setPrefetchCount(prefetchCount);
            }
        }
        return "ok";
    }

}
